import CryptoJS from "crypto-js";
import config from "@/utils/config";

const secret_key = config.appInfo.key;
const iv = config.appInfo.iv;

const options = {
  iv: CryptoJS.enc.Utf8.parse(iv),
  mode: CryptoJS.mode.CBC,
  padding: CryptoJS.pad.Pkcs7
};
const key = CryptoJS.enc.Utf8.parse(secret_key);
//加密
export function encrypt(plaintText) {
  if (plaintText) {
    const srcs = CryptoJS.enc.Utf8.parse(
      typeof plaintText == "object" ? JSON.stringify(plaintText) : plaintText
    );
    const cipher = CryptoJS.AES.encrypt(srcs, key, options);
    const base64Cipher = cipher.ciphertext.toString(CryptoJS.enc.Base64);
    return base64Cipher;
  }
  return plaintText;
}

//解密
export function decrypt(encryptedBase64Str) {
  if (!encryptedBase64Str) return;
  if (encryptedBase64Str instanceof Object) return encryptedBase64Str;
  if (encryptedBase64Str.indexOf("resourceId") !== -1) {
    return encryptedBase64Str;
  }
  if (
    typeof Number(encryptedBase64Str) === "number" &&
    !isNaN(Number(encryptedBase64Str))
  )
    return encryptedBase64Str;
  const decryptedData = CryptoJS.AES.decrypt(
    encryptedBase64Str.toString(),
    key,
    options
  );
  const decryptedBase64Str = decryptedData.toString(CryptoJS.enc.Utf8);
  return JSON.parse(decryptedBase64Str);
}
